//
//  UserAccountViewModel.swift
//  JJWeibo
//
//  Created by JJ on 15/9/4.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import ReactiveCocoa

class UserAccountViewModel: NSObject {

    static let sharedUserAccount=UserAccountViewModel()
    
    var userAccount:UserAccount?
    
    override init() {
        userAccount=UserAccount.loadUserAccount()
    }
    
    var accessToken:String?{
        return userAccount?.access_token
    }
    
    var userLogon: Bool {
        return accessToken != nil
    }
    
    var avatarUrl:NSURL?{
        return NSURL(string: userAccount?.avatar_large ?? "")
    }
    
    func loadUserAccount(code: String) -> RACSignal  {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
                NetWorkTools.shareNetWorkTools.loadReccessToKen(code).doNext({ (result) -> Void in
                
                let account = UserAccount(dic: result as! [String: AnyObject])
                // 设置当前的账户属性
                self.userAccount = account
//                printLog(account)
                
                NetWorkTools.shareNetWorkTools.loadUserInfo(account.uid!).subscribeNext({ (result) -> Void in
                    
                    let dict = result as! [String: AnyObject]
                    // 设置帐号的属性`
                    account.name = dict["name"] as? String
                    account.avatar_large = dict["avatar_large"] as? String
                    
                    // 保存账号
                    account.saveUserAcount()
                    
                    // 通知订阅者网络数据加载完成
                    subscriber.sendCompleted()
                    
                    }, error: { (error) -> Void in
                        subscriber.sendError(error)
                })
            }).subscribeError({ (error) -> Void in
                subscriber.sendError(error)
            })
            
            return nil
        })
        
        }
}








